#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>
#include <cerrno>
#include "log_pro.hpp"
using namespace std;

void setNonBlock(int fd)//可以传递不同文件，修改不同文件为非阻塞等待
{
    int flag = fcntl(fd, F_GETFL);
    if (flag < 0)
    {
        lg(ERROR, "fcntl file erroron:%d,%s", errno, strerror(errno));
        exit(-1);
    }
    else
    {
        fcntl(0, F_SETFL, flag | O_NONBLOCK);
    }
}

int main()
{
    setNonBlock(0);
    //close(0);//测试关闭标准输入，产生真正读错误的情况
    char buffer[1024] = {0};
    int count =0;
    while (true)
    {
        //cout << "please enter:" << flush;
        int n = read(0, buffer, sizeof(buffer) - 1);
        if (n < 0)
        {
            //测试出如果只是读文件还没就绪错误码为11：EWOULDBLOCK
            if(errno==EWOULDBLOCK)
            {
                lg(NOTICE,"文件未就绪... %d",++count);
                sleep(1);
            }
            else
            {
                lg(ERROR,"read error! erroron:%d,%s", errno, strerror(errno));
                break;
            }
        }
        else if (n == 0)
        {
            lg(NOTICE, "file close! quit");
            break;
        }
        else
        {
            buffer[n - 1] = 0;
            cout << "echo:" << buffer << endl;
        }
    }

    return 0;
}